package com.briup.jd2511.jd2511bookstore.filter;

import com.briup.jd2511.jd2511bookstore.exception.ServiceException;
import com.briup.jd2511.jd2511bookstore.response.ResultCode;
import com.briup.jd2511.jd2511bookstore.utils.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
// @WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("login filter 初始化。。。");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 判断请求是否是/login，请求方法是否是OPTIONS，如果是就放行
        if (request.getRequestURI().endsWith("/login") ||
                request.getMethod().equalsIgnoreCase("OPTIONS")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 输出当前拦截的url
        log.info("当前拦截的url是：{}", request.getRequestURL());

        // 获取请求头中的token
        String token = request.getHeader("token");
        log.info("当前请求的token是：{}", token);
        // 判断token是否为空，或者是否是空字符串
        if (!StringUtils.hasText(token)) {
            throw new ServiceException(ResultCode.TOKEN_MISSION);
        }
        // 解析token，捕获其中的异常
        try {
            JwtUtil.parseJWT(token);
        }catch (Exception e){
            log.error("过滤器中的异常捕获，传递给controller进行处理");
            request.setAttribute("exception", e);
            // 跳转到新地址
            request.getRequestDispatcher("/filterError")
                    .forward(request, response);
            return;
        }
//        catch (ExpiredJwtException e){
//            log.error("token已过期");
//            throw new ServiceException(ResultCode.TOKEN_TIMEOUT);
//        } catch (Exception e){
//            log.error("token解析失败");
//            throw new ServiceException(ResultCode.TOKEN_IS_INVALID);
//        }
        // 验证token中id的有效性

        // 放行
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("login filter 销毁。。。");
    }
}
